package com.api.doc.search.web;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.api.browser.bean.BrowserBean;
import com.api.browser.bean.SearchConditionItem;
import com.api.browser.service.impl.DocCategoryService;
import com.api.browser.service.impl.DocFullSearchUtil;
import com.api.doc.category.service.CategoryService;
import com.api.doc.mobile.systemDoc.util.CategoryUtil;
import com.api.doc.search.bean.CustomFieldExt;
import com.api.doc.search.bean.RightMenu;
import com.api.doc.search.service.DocNewsService;
import com.api.doc.search.service.DocSearchService;
import com.api.doc.search.util.*;
import com.engine.common.util.ParamUtil;
import com.engine.doc.util.CheckPermission;
import com.engine.doc.util.DocApplySettingUtil;
import com.engine.portal.biz.menuinfo.MenuInfoCommonBiz;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.hrm.moduledetach.ManageDetachComInfo;
import weaver.systeminfo.SystemEnv;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.*;

@Path("/doc/searchlist")
public class SearchListAction {
	/**
	 * 列表
	 * @author wangqs
	 * */
	@GET
	@Path("/list")
	@Produces(MediaType.TEXT_PLAIN)
	public String getDataList(@Context HttpServletRequest request, @Context HttpServletResponse response) throws Exception {
		Map<String,Object> apidatas = new HashMap<String,Object>();
		try{
			User user = HrmUserVarify.getUser (request , response) ;


			String getMost = request.getParameter("getMost");
			boolean noFullSearch = false; //微搜不支持，只能走sql
			
			if("reply".equals(getMost) || "read".equals(getMost) || "download".equals(getMost) || "score".equals(getMost)){
				noFullSearch = true;
			}
			
			//当前选中tab
			int tabInfo = Util.getIntValue(request.getParameter(ConditionUtil.TAB_REQ_NAME),ConditionUtil.TAB_LIST_DEFAULT);
			
			boolean fromProtal = false;
			String protalViewcondition = "";
			DocTableType docTableType = null;
			
			if(tabInfo == ConditionUtil.TAB_LIST_MY){
				docTableType = DocTableType.MY_DOC_TABLE;
			}else if(tabInfo == ConditionUtil.TAB_LIST_NO_READ){
				docTableType = DocTableType.NO_READ_DOC;
				noFullSearch = true;
			}else if(tabInfo >= ConditionUtil.TAB_LIST_ALL){
				docTableType = DocTableType.SEARCH_DOC_TABLE;
			}
			//外部用户暂不支持微搜
			if("2".equals(user.getLogintype())){
				noFullSearch=true;
			}
			
			DocSearchService docSearchService = new DocSearchService();
			boolean useFullSearch = noFullSearch ? false : DocSearchService.useFullSearch();
			//boolean hasFullSearch = noFullSearch ? false : DocFullSearchUtil.isUseFullSearch(user.getLanguage() + "");

			String elementmore = Util.null2String(request.getParameter("elementmore"));

			String secIds = "";
			String dumids = "";
			String cenids = "";
			String poids = "";
			String toids = "";
			String order = "";
			String orderBy = "";

			if(!elementmore.isEmpty())
			{
				//net.sf.json.JSONArray arry = net.sf.json.JSONArray.fromObject(elementmore);
				//net.sf.json.JSONObject jb = arry.getJSONObject(0);
				net.sf.json.JSONObject jb = net.sf.json.JSONObject.fromObject(elementmore);
				
				if(jb.get(DocNewsService.NEWS_CATEGORY_IDS) != null){
					useFullSearch = false;
					String jonStr = jb.getString(DocNewsService.NEWS_CATEGORY_IDS);
					net.sf.json.JSONArray arry = net.sf.json.JSONArray.fromObject(jonStr);
					for(int i = 0;i < arry.size();i++){
						secIds += "," + arry.getInt(i);
					}
					secIds = secIds.isEmpty() ? "" : secIds.substring(1);
				}
				
				if(jb.get(DocNewsService.NEWS_VIRTUAL_IDS) != null){
					useFullSearch = false;
					String jonStr = jb.getString(DocNewsService.NEWS_VIRTUAL_IDS);
					net.sf.json.JSONArray arry = net.sf.json.JSONArray.fromObject(jonStr);
					for(int i = 0;i < arry.size();i++){
						dumids += "," + arry.getInt(i);
					}
					dumids = dumids.isEmpty() ? "" : dumids.substring(1);
				}
				
				if(jb.get(DocNewsService.NEWS_CENTER_IDS) != null){
					useFullSearch = false;
					String jonStr = jb.getString(DocNewsService.NEWS_CENTER_IDS);
					net.sf.json.JSONArray arry = net.sf.json.JSONArray.fromObject(jonStr);
					for(int i = 0;i < arry.size();i++){
						cenids += "," + arry.getInt(i);
					}
					cenids = cenids.isEmpty() ? "" : cenids.substring(1);
				}
				
				if(jb.get(DocNewsService.NEWS_APPOINT_IND) != null){
					useFullSearch = false;
					String jonStr = jb.getString(DocNewsService.NEWS_APPOINT_IND);
					net.sf.json.JSONArray arry = net.sf.json.JSONArray.fromObject(jonStr);
					for(int i = 0;i < arry.size();i++){
						poids += "," + arry.getInt(i);
					}
					poids = poids.isEmpty() ? "" : poids.substring(1);
				}
				
				if(jb.get(DocNewsService.NEWS_TOP_IDS) != null){
					useFullSearch = false;
					String jonStr = jb.getString(DocNewsService.NEWS_TOP_IDS);
					net.sf.json.JSONArray arry = net.sf.json.JSONArray.fromObject(jonStr);
					for(int i = 0;i < arry.size();i++){
						toids += "," + arry.getInt(i);
					}
					toids = toids.isEmpty() ? "" : toids.substring(1);
				}
				
				order = "";
				orderBy = "";
			}
			
			String secid = Util.null2String(request.getParameter("secid"));
			if(!secid.isEmpty()){
				secIds += secIds.isEmpty() ? secid : ("," + secid);
			}
			String menuid = Util.null2String(request.getParameter("menuidforportal"));
			if (!menuid.isEmpty()){
				String paramsStr = new MenuInfoCommonBiz().getLeftMenuParams(menuid);
				secid = getUrlParams(paramsStr,"secid");
				int viewcondition = Util.getIntValue(getUrlParams(paramsStr,"viewcondition"));
				if(!secid.isEmpty()){
					secIds += secIds.isEmpty() ? secid : ("," + secid);
				}
				if(viewcondition == ConditionUtil.TAB_LIST_MY){
					docTableType = DocTableType.MY_DOC_TABLE;
					fromProtal = true;
					protalViewcondition = ConditionUtil.TAB_LIST_MY+"";
				}else if(viewcondition == ConditionUtil.TAB_LIST_NO_READ){
					docTableType = DocTableType.NO_READ_DOC;
					fromProtal = true;
					protalViewcondition = ConditionUtil.TAB_LIST_NO_READ+"";
					useFullSearch = false;
				}else if(viewcondition >= ConditionUtil.TAB_LIST_ALL){
					docTableType = DocTableType.SEARCH_DOC_TABLE;
					fromProtal = true;
					protalViewcondition = ConditionUtil.TAB_LIST_ALL+"";
				}

			}
			
			apidatas.put("secids",secIds); 
			apidatas.put("elementmore",elementmore);
			if(useFullSearch){
				Map<String,Object> params = new HashMap<String,Object>();
				String groupid = request.getParameter("groupid");   //自定义查询
				ConditionUtil condition = new ConditionUtil();
				if(tabInfo > ConditionUtil.TAB_LIST_ALL && groupid != null && !groupid.isEmpty()){
					Map<String,String> defaultValues = condition.getConditionMouldDetail(groupid, user);
					for(String key : defaultValues.keySet()){
						params.put(key, defaultValues.get(key));
					}
				}else{
					params = getRequestMap(request);
				}

				if(!secIds.isEmpty())
				{
					params.put("secCategory", secIds);

				}
				apidatas = docSearchService.getDocListByFullSearch(docTableType,user,params);
				apidatas.put("useType", "datasource");
			}else{
				DocListUtil docListUtil = new DocListUtil(request,user,docTableType);
				String detailWhere = docListUtil.getSqlWhere();
//				ayh
//				new BaseBean().writeLog("docListUtil get sql string！");

				String moreWhere = "";
				if(!secIds.isEmpty())
				{
					moreWhere += " or t1.seccategory in ("+secIds+")";
				}
				if(!dumids.isEmpty()){
					moreWhere += " or exists (select 1 from DocDummyDetail where docid=t1.id and catelogid in("+dumids+"))";
				}
				if(!cenids.isEmpty()){

					RecordSet rs = new RecordSet();
					rs.executeQuery("select publishtype,departmentopt,dateopt,newsclause from DocFrontpage where id in(" + cenids + ")");
					
					
					String newsWhere = "";
					
					int publishtype = 0;
					int departmentopt = 0;
					int dateopt = 0;
					String newsclause = "";
					while(rs.next()){
						publishtype = rs.getInt("publishtype");
						departmentopt = rs.getInt("departmentopt");
						dateopt = rs.getInt("dateopt");
						newsclause = rs.getString("newsclause");
					
						newsWhere += " or (";
						if(publishtype > 0){
							newsWhere += " t1.docpublishtype='" + publishtype + "'";
						}else{
							newsWhere += " t1.docpublishtype in('2','3')";
						}
						
						if(departmentopt > 0){
							newsWhere += " and t1.docdepartmentid=" + departmentopt ;
						}
						
						if(dateopt > 0){
							
							Calendar calendar = Calendar.getInstance();
							calendar.add(Calendar.DATE, -30);
							String date = TimeUtil.getDateString(calendar);
							
							newsWhere += " and t1.doclastmoddate>='" + date + "'" ;
						}
						
						if(!newsclause.isEmpty()){
							newsWhere += " and " + newsclause;
						}
						newsWhere += ")";
					}
					
				}
				
				String ids = toids + "," + poids;
				
				ids = ids.startsWith(",") ? ids.substring(1) : ids;
				ids = ids.endsWith(",") ? ids.substring(0,ids.length() - 1) : ids;
				
				if(!ids.isEmpty()){
					moreWhere += " or t1.id in(" + ids + ")";
				}
				
				
				if(!moreWhere.isEmpty()){
					detailWhere += " and (" + moreWhere.substring(4) + ")";
				}
				
				int seccategory = Util.getIntValue(request.getParameter(DocCondition.SEC_CATEGORY.getName()),0);
				String _secid = secIds;
				if(seccategory > 0){
					_secid = _secid.isEmpty() ? (seccategory+"") : (_secid + "," + seccategory);
				}
				
				Map<String,String> createDateMap = DocListUtil.getCreateDate(request);
				createDateMap.put(DocCondition.SEC_CATEGORY.getName(),_secid);

				DocShareUtil docShareUtil = new DocShareUtil(user,detailWhere,createDateMap);
				String shareTable = docShareUtil.getSqlShare();
				
				
				Map<String,String> params = new HashMap<String,String>();
				params.put("getMost", request.getParameter("getMost"));
				
				String getLog = new BaseBean().getPropValue("doc_full_search","sqlLog");
				if("1".equals(getLog))
					params.put("showTableString","1");

				if(seccategory > 0){
					boolean useCustomSearch = docSearchService.isUseCustomSearch(seccategory);
					params.put("useCustomSearch",useCustomSearch ? "1" : "0");
				}

				apidatas = docSearchService.getDocList(detailWhere,shareTable,seccategory,docTableType,user,params);
				apidatas.put("useType", "sql");
				apidatas.put("seccategoryid",seccategory);
				apidatas.put("fromPortal",fromProtal?"1":"0");
				apidatas.put("protalViewcondition",protalViewcondition);
				apidatas.put("canCreate",true);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			apidatas.put("api_status", false);
			apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
		}
		return JSONObject.toJSONString(apidatas);	
	}
	
	/**
	 * 保存自定义查询模板
	 * @author wangqs
	 * */
	@GET
	@Path("/saveConditionMould")
	@Produces(MediaType.TEXT_PLAIN)
	public String saveConditionMould(@Context HttpServletRequest request, @Context HttpServletResponse response) throws Exception {
		Map<String,Object> apidatas = new HashMap<String,Object>();
		try{
			User user = HrmUserVarify.getUser (request , response) ;
			
			String conditionMouldId = Util.null2String(request.getParameter("conditionMouldId"));
			String conditionMouldName = Util.null2String(request.getParameter("conditionMouldName"));
			
			Map<String,Object> conditionMap = getRequestMap(request);
			
			ConditionUtil conditionUtil = new ConditionUtil();
			apidatas = conditionUtil.saveConditionMould(conditionMouldId, conditionMouldName, user, conditionMap);
			
		}catch (Exception e) {
			e.printStackTrace();
			apidatas.put("api_status", false);
			apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
		}
		return JSONObject.toJSONString(apidatas);	
	}
	
	/**
	 * 删除自定义查询模板
	 * @author wangqs
	 * */
	@GET
	@Path("/deleteConditionMould")
	@Produces(MediaType.TEXT_PLAIN)
	public String deleteConditionMould(@Context HttpServletRequest request, @Context HttpServletResponse response) throws Exception {
		Map<String,Object> apidatas = new HashMap<String,Object>();
		try{
			User user = HrmUserVarify.getUser (request , response) ;
			
			String conditionMouldId = Util.null2String(request.getParameter("groupid"));
			
			ConditionUtil conditionUtil = new ConditionUtil();
			apidatas = conditionUtil.deleteConditionMould(conditionMouldId, user);
			
		}catch (Exception e) {
			e.printStackTrace();
			apidatas.put("api_status", false);
			apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
		}
		return JSONObject.toJSONString(apidatas);	
	}
	
	/**
	 * 高级搜索
	 * @author wangqs
	 * */
	@GET
	@Path("/condition")
	@Produces(MediaType.TEXT_PLAIN)
	public String getConDition(@Context HttpServletRequest request, @Context HttpServletResponse response) throws Exception {
		Map<String,Object> apidatas = new HashMap<String,Object>();
		try{
			User user = HrmUserVarify.getUser (request , response) ;
			
			//当前选中tab
			int tabInfo = Util.getIntValue(request.getParameter(ConditionUtil.TAB_REQ_NAME),ConditionUtil.TAB_LIST_DEFAULT);
			
			//目录id
			int secid = Util.getIntValue(request.getParameter(DocCondition.SEC_CATEGORY.getName()));
			
			List<Map<String,Object>> grouplist = new ArrayList<Map<String,Object>>();
			
			Map<String,Object> groupitem1 = new HashMap<String,Object>();
			List<SearchConditionItem> itemlist1 = new ArrayList<SearchConditionItem>();
			groupitem1.put("title", SystemEnv.getHtmlLabelNames(ConditionUtil.COMMON_CONDITION, user.getLanguage()));
			groupitem1.put("defaultshow", true);
			groupitem1.put("items", itemlist1);
			grouplist.add(groupitem1);
			
			Map<String,String> defaultValues = new HashMap<String,String>();
			if(tabInfo > ConditionUtil.TAB_LIST_ALL){
				String groupid = request.getParameter("groupid");   //自定义查询
				if(groupid != null && !groupid.isEmpty()){
					ConditionUtil condition = new ConditionUtil();
					defaultValues = condition.getConditionMouldDetail(groupid, user);
				}
			}
			
			
			itemlist1.add(ConditionUtil.getCondition(DocCondition.DOC_SUBJECT,user,
					defaultValues.get(DocCondition.DOC_SUBJECT.getName())));
			
			boolean secretFlag = CheckPermission.isOpenSecret();
			if(secretFlag){
				//String tableType = request.getParameter("tableType");
				//if("propSet".equals(tableType)){
				//	itemlist1.add(ConditionUtil.getSecretLevel(user));
				//}else{
					itemlist1.add(ConditionUtil.getCondition(DocCondition.SECRET_LEVEL,user,
							defaultValues.get(DocCondition.SECRET_LEVEL.getName())));
				//}
			}
			
			if(ConditionUtil.TAB_LIST_MY == tabInfo){  //我的文档
				itemlist1.add(ConditionUtil.getDocStatus2(user.getLanguage()));
			}else if(ConditionUtil.TAB_LIST_NO_READ == tabInfo || ConditionUtil.TAB_LIST_ALL <= tabInfo){ // 未读文档、全部文档
				itemlist1.add(ConditionUtil.getCondition(DocCondition.DOC_CREATER_ID,user,
						defaultValues.get(DocCondition.DOC_CREATER_ID.getName())));
			}
			//增加属性，目录浏览框过滤隐藏目录
			SearchConditionItem searchConditionItem=ConditionUtil.getCondition(DocCondition.SEC_CATEGORY,user,
					defaultValues.get(DocCondition.SEC_CATEGORY.getName()));
			BrowserBean browserBean= searchConditionItem.getBrowserConditionParam();
			Map<String,Object> browserparams= browserBean.getDataParams();
			browserparams.put("ishidesec","1");
			browserBean.getCompleteParams().put("ishidesec","1");
			itemlist1.add(searchConditionItem);
			itemlist1.add(ConditionUtil.getCondition(DocCondition.DOC_CREATEDATE_SELECT,user,
					defaultValues.get(DocCondition.DOC_CREATEDATE_SELECT.getName())));
			itemlist1.add(ConditionUtil.getCondition(DocCondition.DOC_NO,user,
					defaultValues.get(DocCondition.DOC_NO.getName())));
			//itemlist1.add(ConditionUtil.getCondition(DocCondition.DATE2DURING,user));
			itemlist1.add(ConditionUtil.getCondition(DocCondition.DOC_LAST_MODDATE,user,
					defaultValues.get(DocCondition.DOC_LAST_MODDATE.getName())));
			
			Map<String,Object> groupitem2 = new HashMap<String,Object>();
			List<SearchConditionItem> itemlist2 = new ArrayList<SearchConditionItem>();
			groupitem2.put("title", SystemEnv.getHtmlLabelNames(ConditionUtil.OTHER_CONDITION,user.getLanguage()));
			groupitem2.put("defaultshow", true);
			groupitem2.put("items", itemlist2);
			grouplist.add(groupitem2);
			
			if(ConditionUtil.TAB_LIST_NO_READ == tabInfo || ConditionUtil.TAB_LIST_ALL <= tabInfo){ // 未读文档、全部文档
				itemlist2.add(ConditionUtil.getCondition(DocCondition.DEPARTMENT_ID,user,
						defaultValues.get(DocCondition.DEPARTMENT_ID.getName())));
				itemlist2.add(ConditionUtil.getCondition(DocCondition.OWNER_ID,user,
						defaultValues.get(DocCondition.OWNER_ID.getName())));
				itemlist2.add(ConditionUtil.getCondition(DocCondition.OWNER_DEPARTMENT_ID,user,
						defaultValues.get(DocCondition.OWNER_DEPARTMENT_ID.getName())));
				itemlist2.add(ConditionUtil.getCondition(DocCondition.OWNER_SUBCOMPANY_ID,user,
						defaultValues.get(DocCondition.OWNER_SUBCOMPANY_ID.getName())));
				itemlist2.add(ConditionUtil.getCondition(DocCondition.CREATER_SUBCOMPANY_ID,user,
						defaultValues.get(DocCondition.CREATER_SUBCOMPANY_ID.getName())));
			}
			itemlist2.add(ConditionUtil.getCondition(DocCondition.DOC_PUBLISH_TYPE,user,
					defaultValues.get(DocCondition.DOC_PUBLISH_TYPE.getName())));
			//if(ConditionUtil.TAB_LIST_NO_READ == tabInfo){
				itemlist2.add(ConditionUtil.getCondition(DocCondition.TREE_DOC_FIELD_ID,user));
			//}
			itemlist2.add(ConditionUtil.getCondition(DocCondition.KEYWORD,user,
					defaultValues.get(DocCondition.KEYWORD.getName())));
			itemlist2.add(ConditionUtil.getCondition(DocCondition.REPLAY_DOC_COUNT,user,
					defaultValues.get(DocCondition.REPLAY_DOC_COUNT.getName())));
			if(ConditionUtil.TAB_LIST_NO_READ == tabInfo || ConditionUtil.TAB_LIST_ALL <= tabInfo){ // 未读文档、全部文档
				itemlist2.add(ConditionUtil.getDocStatus1(user.getLanguage()));
				//itemlist2.add(ConditionUtil.getCondition(DocCondition.DOC_LANGURAGE,user,
				//		defaultValues.get(DocCondition.DOC_LANGURAGE.getName())));
				itemlist2.add(ConditionUtil.getCondition(DocCondition.DOC_LAST_MODUSER_ID,user,
						defaultValues.get(DocCondition.DOC_LAST_MODUSER_ID.getName())));
				itemlist2.add(ConditionUtil.getCondition(DocCondition.DOC_ARCHIVE_DATE,user,
						defaultValues.get(DocCondition.DOC_ARCHIVE_DATE.getName())));
				itemlist2.add(ConditionUtil.getCondition(DocCondition.DOC_ARCHIVE_USER_ID,user,
						defaultValues.get(DocCondition.DOC_ARCHIVE_USER_ID.getName())));
				itemlist2.add(ConditionUtil.getCondition(DocCondition.DOC_APPROVE_DATE,user,
						defaultValues.get(DocCondition.DOC_APPROVE_DATE.getName())));
				itemlist2.add(ConditionUtil.getCondition(DocCondition.DOC_APPROVE_USER_ID,user,
						defaultValues.get(DocCondition.DOC_APPROVE_USER_ID.getName())));
				
				itemlist2.add(ConditionUtil.getCondition(DocCondition.CRMID,user,
						defaultValues.get(DocCondition.CRMID.getName())));
				itemlist2.add(ConditionUtil.getCondition(DocCondition.ASSETID,user,
						defaultValues.get(DocCondition.ASSETID.getName())));
				itemlist2.add(ConditionUtil.getCondition(DocCondition.HRMRESID,user,
						defaultValues.get(DocCondition.HRMRESID.getName())));
				itemlist2.add(ConditionUtil.getCondition(DocCondition.PROJECTID,user,
						defaultValues.get(DocCondition.PROJECTID.getName())));
			}
			
			
			//自定义字段
			if(secid > 0){
				List<SearchConditionItem> itemlist3 = ConditionUtil.getCustomFieldExtProxyNew(secid, user);
				
				if(itemlist3 != null && itemlist3.size() > 0){
				
					Map<String,Object> groupitem3 = new HashMap<String,Object>();
					groupitem3.put("title", SystemEnv.getHtmlLabelNames(ConditionUtil.CUSTOM_CONDITION,user.getLanguage()));
					groupitem3.put("defaultshow", false);
					groupitem3.put("items", itemlist3);
					grouplist.add(groupitem3);
				}
				
			}
		
			apidatas.put("condition", grouplist);
		} catch (Exception e) {
			e.printStackTrace();
			apidatas.put("api_status", false);
			apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
		}

		// 禁止序列化时，同一个对象产生引用
		return JSONObject.toJSONString(apidatas, SerializerFeature.DisableCircularReferenceDetect);
	}
	
	/**
	 * 树结构
	 * @author wangqs
	 * */
	@GET
	@Path("/treeNode")
	@Produces(MediaType.TEXT_PLAIN)
	public String getTreeData(@Context HttpServletRequest request, @Context HttpServletResponse response) throws Exception {
		Map<String,Object> apidatas = new HashMap<String,Object>();
		try{
			
			//当前选中tab
			int tabInfo = Util.getIntValue(request.getParameter(ConditionUtil.TAB_REQ_NAME),ConditionUtil.TAB_LIST_DEFAULT);
			BaseBean bb = new BaseBean();
			User user = HrmUserVarify.getUser (request , response) ;
			CategoryTree tree = new CategoryTree();
			
			String isCommon = Util.null2String(request.getParameter("isCommon"));
			String isFav = Util.null2String(request.getParameter("isFav"));
			
			int type = CategoryTree.ALL;
			if("1".equals(isCommon)){
				type = CategoryTree.COMMON;
			}else if("1".equals(isFav)){
				type = CategoryTree.FAV;
			}
			
			Map<String,String> dataMap = new HashMap<String,String>();
			String secid = Util.null2String(request.getParameter("secid"));
            String menuid = Util.null2String(request.getParameter("menuidforportal"));
			String firstSecid = Util.null2s(request.getParameter("firstSecid"),"0");
			dataMap.put("firstSecid",firstSecid);
//			bb.writeLog("111111111111111 secid:"+secid+"---menuid:"+menuid+"--firstSecid:"+firstSecid);
            if (!menuid.isEmpty()){
				String paramsStr = new MenuInfoCommonBiz().getLeftMenuParams(menuid);
				paramsStr =  (paramsStr.indexOf("?")>0 ? "" : "?") +paramsStr;
				secid = getUrlParams(paramsStr,"secid");
            }

			if(!secid.isEmpty()){
				dataMap.put("secid",secid);
			}
//			bb.writeLog("222222222222222 secid:"+secid+"---menuid:"+menuid+"--dataMap:"+dataMap+"---type:"+type+"--tabInfo:"+tabInfo);
			String getLog = new BaseBean().getPropValue("doc_full_search","sqlLog");
			if("1".equals(getLog))
				tree.setGetSql(true);
			
			String treeJson = "";
			if(tabInfo == ConditionUtil.TAB_LIST_MY){
				treeJson = tree.getTree(user,DocTableType.MY_DOC_TABLE,"",type,dataMap);
			}else if(tabInfo == ConditionUtil.TAB_LIST_NO_READ){
				treeJson = tree.getTree(user,DocTableType.NEWEST_DOC,"",type,dataMap);
			}else if(tabInfo >= ConditionUtil.TAB_LIST_ALL){
				treeJson = tree.getTree(user,DocTableType.SEARCH_DOC_TABLE,"",type,dataMap);
			}
//			bb.writeLog("3333333333333333 secid:"+secid+"---menuid:"+menuid+"--treeJson:"+treeJson);
			return treeJson;
		} catch (Exception e) {
			e.printStackTrace();
			apidatas.put("api_status", false);
			apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
		}
		return JSONObject.toJSONString(apidatas);
	}
	
	/**
	 * 树结构数
	 * @author wangqs
	 * */
	@POST
	@Path("/treeNodeNum")
	@Produces(MediaType.TEXT_PLAIN)
	public String getTreeDataNum(@Context HttpServletRequest request, @Context HttpServletResponse response) throws Exception {
		Map<String,Object> apidatas = new HashMap<String,Object>();
		try{
			
			//当前选中tab
			int tabInfo = Util.getIntValue(request.getParameter(ConditionUtil.TAB_REQ_NAME),ConditionUtil.TAB_LIST_DEFAULT);
			
			
			User user = HrmUserVarify.getUser (request , response) ;
			CategoryTree tree = new CategoryTree();
			
			String isCommon = Util.null2String(request.getParameter("isCommon"));
			String isFav = Util.null2String(request.getParameter("isFav"));
			
			int type = CategoryTree.ALL;
			if("1".equals(isCommon)){
				type = CategoryTree.COMMON;
			}else if("1".equals(isFav)){
				type = CategoryTree.FAV;
			}
			//处理异步加载目录num的逻辑start====
			Map<String,String> dataMap = new HashMap<String,String>();
			String secid = Util.null2String(request.getParameter("secid"));
			String selectChild = Util.null2s(request.getParameter("selectChild"),"0");
			dataMap.put("selectChild",selectChild);
			if(!secid.isEmpty()){
				dataMap.put("secid",secid);
				if("1".equals(selectChild)&&!secid.contains(",")){
					String childSql = "select id from DocSecCategory where parentid = ?";
					RecordSet rs = new RecordSet();
					rs.executeQuery(childSql,secid);
					String ids="";
					while (rs.next()){
						String id = rs.getString("id");
						ids = ids+","+id;
					}
					if(!ids.isEmpty()) ids = ids.substring(1);
					dataMap.put("secid",ids);
				}
				dataMap.put("asynnum","1");
			}
			
			String getLog = new BaseBean().getPropValue("doc_full_search","sqlLog");
			if("1".equals(getLog))
				tree.setGetSql(true);
			
			//处理异步加载目录num的逻辑end====
			Map<String,Map<String,String>> treeNum = new HashMap<String,Map<String,String>>();
			if(tabInfo == ConditionUtil.TAB_LIST_MY){
				treeNum = tree.getTreeNum(user,DocTableType.MY_DOC_TABLE,"",type,dataMap);
			}else if(tabInfo == ConditionUtil.TAB_LIST_NO_READ){
				treeNum = tree.getTreeNum(user,DocTableType.NEWEST_DOC,"",type,dataMap);
			}else if(tabInfo >= ConditionUtil.TAB_LIST_ALL){
				treeNum = tree.getTreeNum(user,DocTableType.SEARCH_DOC_TABLE,"",type,dataMap);
			}
			
			apidatas.put("treecount", treeNum);
			apidatas.put("countcfg", tree.getTreeNumColor(user,true));
			
		} catch (Exception e) {
			e.printStackTrace();
			apidatas.put("api_status", false);
			apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
		}
		return JSONObject.toJSONString(apidatas);
	}
	
	/**
	 * 右键菜单
	 * @author wangqs
	 * */
	@GET
	@Path("/rightMenu")
	@Produces(MediaType.TEXT_PLAIN)
	public String getRightMenu(@Context HttpServletRequest request, @Context HttpServletResponse response) throws Exception {
		Map<String,Object> apidatas = new HashMap<String,Object>();
		try{
			User user = HrmUserVarify.getUser (request , response) ;
			List<RightMenu> rightMenus = new ArrayList<RightMenu>(); 
			
			String view = Util.null2String(request.getParameter(RightMenu.TABLE_VIEW_PARAM));
			
			int language = user.getLanguage();
			
			//当前选中tab
			int tabInfo = Util.getIntValue(request.getParameter(ConditionUtil.TAB_REQ_NAME),ConditionUtil.TAB_LIST_DEFAULT);
			
			
			rightMenus.add(new RightMenu(language,RightMenuType.BTN_SEARCH,"",false));
			if(tabInfo == ConditionUtil.TAB_LIST_MY){  //我的文档
				rightMenus.add(new RightMenu(language,RightMenuType.BTN_DELETE,"doMuliDelete()", true,true));
			}else if(tabInfo == ConditionUtil.TAB_LIST_NO_READ){ //未读文档
				rightMenus.add(new RightMenu(language,RightMenuType.BTN_SUBSCRIBE,"doSubscribe()", false));
				rightMenus.add(new RightMenu(language,RightMenuType.BTN_SIGN_READED,"signReaded()", true,true));
			}else if(tabInfo >= ConditionUtil.TAB_LIST_ALL){ //全部文档
				rightMenus.add(new RightMenu(language,RightMenuType.BTN_SUBSCRIBE,"doSubscribe()", false));
				rightMenus.add(new RightMenu(language,RightMenuType.BTN_IMPORT_SELECT_TO_DUMMY,"importSelectedToDummy()", true,false));
				rightMenus.add(new RightMenu(language,RightMenuType.BTN_IMPORT_ALL_TO_DUMMY,"importAllToDummy()", false));
				//rightMenus.add(new RightMenu(language,RightMenuType.BTN_BACTH_DOWNLOAD_FILE,"bacthDownloadImageFile()", true,false));
				
			}
			//--------------------------------
			RightMenu createDocRightMenu = new RightMenu(language, RightMenuType.BTN_CREATE_DOC, "", true, true);
			//判断是否开启了知识分权，开启了分权增加高级搜索按钮
			boolean useDocManageDetach = new ManageDetachComInfo().isUseDocManageDetach();
			if (useDocManageDetach){
				HashMap map = new HashMap();
				map.put("isHasAdvanceSerach",true);
				createDocRightMenu.setCustomData(map);
			}
			rightMenus.add(createDocRightMenu);
			//--------------------------------
			
			if(DocSearchService.thumbnail){
				if(RightMenu.TABLE_VIEW_VIEW.equals(view)){
					rightMenus.add(new RightMenu(language,RightMenuType.BTN_LIST_DISPLAY,"",false));
				}else{
					RightMenu rMenu = new RightMenu(language,RightMenuType.BTN_MINIATURE_DISPLAY,"",false);
					rMenu.setParams(RightMenu.TABLE_VIEW_PARAM + "=" + RightMenu.TABLE_VIEW_VIEW);
					rightMenus.add(rMenu);
				}
			}
			rightMenus.add(new RightMenu(language,RightMenuType.BTN_COLUMN,"",false));
		//	rightMenus.add(new RightMenu(language,RightMenuType.BTN_STORE,"",false));
		//	rightMenus.add(new RightMenu(language,RightMenuType.BTN_HELP,"",false));
			
			apidatas.put("rightMenus", rightMenus);
		} catch (Exception e) {
			e.printStackTrace();
			apidatas.put("api_status", false);
			apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
		}
		return JSONObject.toJSONString(apidatas);
	}
	
	/**
	 * TAB页
	 * @author wangqs
	 * */
	@GET
	@Path("/tabInfo")
	@Produces(MediaType.TEXT_PLAIN)
	public String getTabInfo(@Context HttpServletRequest request, @Context HttpServletResponse response) throws Exception {
		Map<String,Object> apidatas = new HashMap<String,Object>();
		try{
			User user = HrmUserVarify.getUser (request , response) ;
			
			int _default = ConditionUtil.TAB_LIST_DEFAULT;
			
			List<Map<String,Object>> groupinfo = new ArrayList<Map<String,Object>>();
			String protalViewcondition = "";
			boolean fromProtal = false;
			String menuid = Util.null2String(request.getParameter("menuidforportal"));
			if (!menuid.isEmpty()){
				String paramsStr = new MenuInfoCommonBiz().getLeftMenuParams(menuid);
				int viewcondition = Util.getIntValue(getUrlParams(paramsStr,"viewcondition"));
				if(viewcondition == ConditionUtil.TAB_LIST_MY){
					protalViewcondition = ConditionUtil.TAB_LIST_MY+"";
					fromProtal = true;
				}else if(viewcondition == ConditionUtil.TAB_LIST_NO_READ){
					protalViewcondition = ConditionUtil.TAB_LIST_NO_READ+"";
					fromProtal = true;
				}else if(viewcondition >= ConditionUtil.TAB_LIST_ALL){
					protalViewcondition = ConditionUtil.TAB_LIST_ALL+"";
					fromProtal = true;
				}
			}

			if((fromProtal && "0".equals(protalViewcondition))||!fromProtal){
				Map<String,Object> myDoc = new HashMap<String,Object>();
				myDoc.put("color","");
				myDoc.put("selected",ConditionUtil.TAB_ALL_VALUE == _default);
				myDoc.put("groupid","myDoc");
				myDoc.put("editable",false);
				myDoc.put("showcount",false);
				myDoc.put("title",SystemEnv.getHtmlLabelName(1212,user.getLanguage()));
				myDoc.put(ConditionUtil.TAB_REQ_NAME, ConditionUtil.TAB_LIST_MY);
				groupinfo.add(myDoc);
			}

			if((fromProtal && "1".equals(protalViewcondition))||!fromProtal){
				Map<String,Object> noReadDoc = new HashMap<String,Object>();
				noReadDoc.put("color","");
				noReadDoc.put("selected",ConditionUtil.TAB_TODAY_VALUE == _default);
				noReadDoc.put("groupid","noReadDoc");
				noReadDoc.put("editable",false);
				noReadDoc.put("showcount",false);
				noReadDoc.put("title",SystemEnv.getHtmlLabelName(18441,user.getLanguage()));
				noReadDoc.put(ConditionUtil.TAB_REQ_NAME, ConditionUtil.TAB_LIST_NO_READ);
				groupinfo.add(noReadDoc);
			}
			if((fromProtal && "2".equals(protalViewcondition))||!fromProtal){
				Map<String,Object> allDoc = new HashMap<String,Object>();
				allDoc.put("color","");
				allDoc.put("selected",ConditionUtil.TAB_WEEK_VALUE == _default);
				allDoc.put("groupid","allDoc");
				allDoc.put("editable",false);
				allDoc.put("showcount",false);
				allDoc.put("title",SystemEnv.getHtmlLabelName(30898,user.getLanguage()));
				allDoc.put(ConditionUtil.TAB_REQ_NAME, ConditionUtil.TAB_LIST_ALL);
				groupinfo.add(allDoc);
			}
			if(!fromProtal){
				ConditionUtil conditionUtil = new ConditionUtil();
				List<Map<String,String>> conditionTabs = conditionUtil.getConditionMould("", user);
				int count = 1;
				for(Map<String,String> conditionTab : conditionTabs){
					Map<String,Object> tab = new HashMap<String,Object>();
					tab.put("color","");
					tab.put("selected",false);
					tab.put("groupid",conditionTab.get("id"));
					tab.put("editable",true);
					tab.put("showcount",false);
					tab.put("title",conditionTab.get("name"));
					tab.put(ConditionUtil.TAB_REQ_NAME, ConditionUtil.TAB_LIST_ALL + count);
					groupinfo.add(tab);
					count++;
				}
			}
			String sql = "insert into doc_user_introstep(userid,stepstatus) values(?,?)";
			RecordSet rs = new RecordSet();
			rs.executeUpdate(sql,user.getUID(),1);
			apidatas.put("groupinfo",groupinfo);
			apidatas.put("fromPortal",fromProtal?"1":"0");
			apidatas.put("protalViewcondition",protalViewcondition);
		} catch (Exception e) {
			e.printStackTrace();
			apidatas.put("api_status", false);
			apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
		}
		return JSONObject.toJSONString(apidatas);	
	}

	/**
	 * 获取默认目录配置
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@GET
	@Path("/defaultTreeNode")
	@Produces(MediaType.TEXT_PLAIN)
	public String defaultTreeNode(@Context HttpServletRequest request, @Context HttpServletResponse response) {
		Map<String, Object> apidatas = new HashMap<String, Object>();
		User user = HrmUserVarify.getUser (request , response) ;
		try {
			BaseBean bb = new BaseBean();
			//默认目录树配置 0 ：全部目录 1：收藏目录
			String default_treenode = Util.null2String(bb.getPropValue("doc_full_search","default_treenode")) ;
			default_treenode = "0".equals(default_treenode) ? default_treenode : "1";
			apidatas.put("default_treenode",default_treenode);
			
			boolean showLeftTree = DocApplySettingUtil.getDocTreeOpen();
			apidatas.put("showLeftTree",showLeftTree);
			String protalViewcondition = "";
			boolean fromProtal = false;
			String menuid = Util.null2String(request.getParameter("menuidforportal"));
			if (!menuid.isEmpty()){
				String paramsStr = new MenuInfoCommonBiz().getLeftMenuParams(menuid);
				int viewcondition = Util.getIntValue(getUrlParams(paramsStr,"viewcondition"));
				if(viewcondition == ConditionUtil.TAB_LIST_MY){
					protalViewcondition = ConditionUtil.TAB_LIST_MY+"";
					fromProtal = true;
				}else if(viewcondition == ConditionUtil.TAB_LIST_NO_READ){
					protalViewcondition = ConditionUtil.TAB_LIST_NO_READ+"";
					fromProtal = true;
				}else if(viewcondition >= ConditionUtil.TAB_LIST_ALL){
					protalViewcondition = ConditionUtil.TAB_LIST_ALL+"";
					fromProtal = true;
				}
			}
			apidatas.put("linkUrl",CategoryService.LINK_URL);
			apidatas.put("linkRout",CategoryService.LINK_ROUT);
			apidatas.put("domKey",CategoryService.DOM_KEY);
			apidatas.put("params",CategoryService.PARAMS + DocSptm.DOC_ROOT_FLAG_VALUE);
			apidatas.put(CategoryService.OPEN_NEW_WINDOW,"1");
			apidatas.put("openNewWind","1");
			apidatas.put("api_status",true);
			apidatas.put("fromPortal",fromProtal?"1":"0");
			apidatas.put("protalViewcondition",protalViewcondition);
		} catch (Exception e) {
			e.printStackTrace();
			apidatas.put("api_status", false);
			apidatas.put("msg", SystemEnv.getHtmlLabelName(500551,user.getLanguage()));// "获取目录树默认配置失败"
			//记录异常日志
			BaseBean baseBean = new BaseBean();
			baseBean.writeLog("SearchListAction--->defaultTreeNode:" + e.getMessage());
		}
		return JSONObject.toJSONString(apidatas);
	}/**
	 * 获取新建文档的链接
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@GET
	@Path("/createUrl")
	@Produces(MediaType.TEXT_PLAIN)
	public String createUrl(@Context HttpServletRequest request, @Context HttpServletResponse response) {
		Map<String, Object> apidatas = new HashMap<String, Object>();
		User user = HrmUserVarify.getUser (request , response) ;
		try {
			CategoryService categoryService = new CategoryService();
			apidatas.put("linkUrl",categoryService.LINK_URL);
			apidatas.put("linkRout",categoryService.LINK_ROUT);
			apidatas.put("domKey",categoryService.DOM_KEY);
			apidatas.put("params",categoryService.PARAMS + DocSptm.DOC_ROOT_FLAG_VALUE);
			apidatas.put(categoryService.OPEN_NEW_WINDOW,"1");
			apidatas.put("openNewWind","1");
			apidatas.put("api_status",true);
		} catch (Exception e) {
			e.printStackTrace();
			apidatas.put("api_status", false);
			apidatas.put("msg",SystemEnv.getHtmlLabelName(500554,user.getLanguage()));//  "获取链接失败"
			//记录异常日志
			BaseBean baseBean = new BaseBean();
			baseBean.writeLog("SearchListAction--->createUrl:" + e.getMessage());
		}
		return JSONObject.toJSONString(apidatas);
	}
	/**
	 * 文档查询页面新建权限的目录浏览按钮
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@GET
	@Path("/createDocCategoryBrowser")
	@Produces(MediaType.TEXT_PLAIN)
	public String createDocCategoryBrowser(@Context HttpServletRequest request, @Context HttpServletResponse response) {
		Map<String, Object> apidatas = new HashMap<String, Object>();
		try {
			User user = HrmUserVarify.getUser(request, response);
			Map<String, Object> params = ParamUtil.request2Map(request);
			apidatas.put("createDocCategoryBrowser", CategoryUtil.getCategoryBrowser(params,user, DocCategoryService.IS_CREATE));//新建文档全部目录
			apidatas.put("api_status",true);

		} catch (Exception e) {
			e.printStackTrace();
			apidatas.put("api_status", false);
			//记录异常日志
			BaseBean baseBean = new BaseBean();
			baseBean.writeLog("SearchListAction--->createDocCategoryBrowser:" + e.getMessage());
		}
		return JSONObject.toJSONString(apidatas);
	}

	@GET
	@Path("/getIntrostep")
	@Produces(MediaType.TEXT_PLAIN)
	public String getIntrostep(@Context HttpServletRequest request, @Context HttpServletResponse response) {
		Map<String, Object> apidatas = new HashMap<String, Object>();
		try {
			User user = HrmUserVarify.getUser(request, response);
			Map<String, Object> params = ParamUtil.request2Map(request);
			String sql = "select stepstatus from doc_user_introstep where userid = ?";
			RecordSet rs = new RecordSet();
			rs.executeQuery(sql,user.getUID());
			Boolean needIntro = true;
			if (rs.next()){
				String status = rs.getString("stepstatus");
				if("1".equals(status)){
					needIntro = false;
				}
			}
			apidatas.put("api_status",true);
			apidatas.put("needIntro",needIntro);
		} catch (Exception e) {
			e.printStackTrace();
			apidatas.put("api_status", false);
			//记录异常日志
			BaseBean baseBean = new BaseBean();
			baseBean.writeLog("SearchListAction--->getIntrostep:" + e.getMessage());
		}
		return JSONObject.toJSONString(apidatas);
	}
	public Map<String,Object> getRequestMap(HttpServletRequest request){
		
		Map<String,Object> dataMap = new HashMap<String,Object>();
		
		Enumeration paramNames = request.getParameterNames(); 
		while (paramNames.hasMoreElements()) { 
			String paramName = (String) paramNames.nextElement(); 
			String paramValue = Util.null2String(request.getParameter(paramName));
			dataMap.put(paramName,paramValue);
		}
		return dataMap;
	}
	public String getUrlParams(String url,String paramname){
		String result = "";
		Map<String, String> mapRequest = new HashMap<String, String>();
		String[] arrSplit=null;
		String strUrlParam=url;
		if(strUrlParam==null){
			return "";
		}
		arrSplit=strUrlParam.split("[&]");
		for(String strSplit:arrSplit){
			String[] arrSplitEqual=null;
			arrSplitEqual= strSplit.split("[=]");
			//解析出键值
			if(arrSplitEqual.length>1){
				//正确解析
				mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
			}else{
				if(arrSplitEqual[0]!=""){
					//只有参数没有值，不加入
					mapRequest.put(arrSplitEqual[0], "");
				}
			}
		}
		if(mapRequest.containsKey(paramname)){
			result = mapRequest.get(paramname);
		}
		return result;
	}
}
